# POLYGON((102.144996643067 8.56333160400391,102.144996643067 23.3927307128908,109.469429016114 23.3927307128908,109.469429016114 8.56333160400391,102.144996643067 8.56333160400391))
import psycopg2
import psycopg2.extras
import sys
from shapely.geometry import box
from shapely.wkt import dumps, loads
import gdal
from gdalconst import *
import os
import constant

def main(resx=0.117292465957718, resy=-0.117292465957718):
	con = None
	try:
		con = psycopg2.connect(host='192.168.3.4', database='fimo', user='rasdaman', password='rasdaman') 
		cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
		cur.execute('SELECT filename, path FROM satorgnightlight')
		rows = cur.fetchall()
		
		for row in rows:
			filename = row["filename"].strip()
			
			path = row["path"].strip()
			#path = os.path.join("/media/EXT/", path)
			path = os.path.join("/var/www/html/", path)
			#inputfilename = os.path.join(path, filename + ".hdf")

			inputfile = os.path.join(path, filename)

			outputfile3 = os.path.join(path.replace("public/SatOrgNightLight", "apom/Resample/SatResampNightLight"), filename + "_3km.tif")
			outputfile6 = os.path.join(path.replace("public/SatOrgNightLight", "apom/Resample/SatResampNightLight"), filename + "_6km.tif")
			outputfile10 = os.path.join(path.replace("public/SatOrgNightLight", "apom/Resample/SatResampNightLight"), filename + "_10km.tif")
			
			if not os.path.exists(os.path.dirname(outputfile3)):
				os.makedirs(os.path.dirname(outputfile3))
			
			re_griding(inputfile, constant.res3x, constant.res3y, outputfile3)
			re_griding(inputfile, constant.res6x, constant.res6y, outputfile6)
			re_griding(inputfile, constant.res10x, constant.res10y, outputfile10)
		

	except psycopg2.DatabaseError, e:
		print 'Error %s' % e    
		sys.exit(1)
	finally:
		if con:
			con.close()

def re_griding(inputfile, resx, resy, ouputfile):
	regrid_command = "gdalwarp -s_srs '+proj=longlat +datum=WGS84' -t_srs '+proj=longlat +datum=WGS84' -ot Float32 -wt Float32 -te 100.1 6.4 111.8 25.6 -tr {0} {1} -r cubic -overwrite {2} {3}".format(resx, resy, inputfile, ouputfile)
	os.system(regrid_command)

if __name__ == '__main__':
	main()